﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EPiServer.Core;
using EPiServer.Core.PropertySettings;
using EPiServer.DataAbstraction;

namespace CustomizablePageReference
{
    /// <summary>
    /// Contains utilities to work with EPiServer settings.
    /// </summary>
    public static class SettingsUtility
    {
        /// <summary>
        /// Updates the settings for property.
        /// </summary>
        /// <param name="property">The property.</param>
        /// <param name="settings">The settings.</param>
        public static void UpdateSettings(PropertyData property, IPropertySettings settings)
        {
            PropertySettingsContainer container;
            var propertySettingsRepository = new PropertySettingsRepository();

            if (property.SettingsContainer != null)
            {
                // Settings container already exists.
                container = property.SettingsContainer;
            }
            else
            {
                // Create new settings container.
                var pageDefinition = PageDefinition.Load(property.PageDefinitionID);
                pageDefinition.SettingsID = Guid.NewGuid();
                pageDefinition.Save();
                container = new PropertySettingsContainer(pageDefinition.SettingsID);
            }

            bool propertySettingsExist = true;
            var wrapper = container.GetSetting(settings.GetType());

            if (wrapper == null)
            {
                // Settings don't exist, create new ones.
                wrapper = new PropertySettingsWrapper();
                propertySettingsExist = false;
            }

            // Update settings.
            wrapper.IsGlobal = false;
            wrapper.PropertySettings = settings;

            if (!propertySettingsExist)
            {
                container.Settings.Add(settings.GetType().FullName, wrapper);
            }

            propertySettingsRepository.Save(container);
        }
    }
}
